package com.study.kt._03coroutines

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking

/**
 * <pre>
 *     author : slx
 *     time   : 2021/04/04
 *     desc   : Flow异常
 * </pre>
 */
fun main() {
    runBlocking {
        // 使用try catch在流的收集阶段捕获异常
        try {
            exceptionFlow().collect {
                println(it)
                // 模拟抛出异常,如果it>1则抛出异常
                /*check(it <= 1) {
                    "Collected $it"
                }*/
            }
        } catch (e: Throwable) {
            println("cache:$e")
        }
    }
}

private fun exceptionFlow(): Flow<Int> = flow {
    for (i in 1..4) {
        delay(100)
        emit(i)
    }
}.map { value ->
    // 流的中间操作模拟异常，也会在流collect处捕获
    check(value <= 1) {
        "Collected $value"
    }
    value + 100
}